package xml

import (
	"errors"
	"fmt"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/util"
	"reflect"
)

func XmlUnmashal2Map(stru interface{}) (map[string]interface{}, error) {
	t := reflect.TypeOf(stru)
	fieldNum := t.NumField()
	newMap := make(map[string]interface{}, fieldNum)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	if t.Kind() != reflect.Struct {
		fmt.Println("Check type error not Struct")
		return newMap, errors.New("Check type error not Struct")
	}
	v := reflect.ValueOf(stru)
	for i := 0; i < fieldNum; i++ {
		fieldName := t.Field(i).Name
		fieldVal := v.FieldByName(fieldName).String()
		tagVal, err := util.GetStructTagValue(stru, "xml", fieldName)
		if err != nil {
			return newMap, err
		}
		if tagVal != "" {
			newMap[tagVal] = fieldVal
		}
	}
	return newMap, nil
}
